if(SSPUtil == null){
    var SSPUtil = {
        css : Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService),        
    }
    
   SSPUtil.$ = function $(id){
        return document.getElementById(id);
    }
    
    SSPUtil.setPref = function(v){
         Application.prefs.setValue('extensions.sspage.mapping', JSON.stringify(v))
    }
    
    SSPUtil.getPref = function(){
         return JSON.parse(Application.prefs.getValue('extensions.sspage.mapping', {})   )     
    }

    SSPUtil.TLDS = Components.classes["@mozilla.org/network/effective-tld-service;1"]
                  .getService(Components.interfaces.nsIEffectiveTLDService);
    
    SSPUtil.getHost = function(aURI){
	return SSPUtil.TLDS.getBaseDomain(aURI);	
   }
    
   SSPUtil.ce = function ce(name, node, data, handles, insertflg, doc){
        var object = document.createElement(name);
        for (var p in data) {
            object.setAttribute(p, data[p])
        }
        for (var p in handles) {
            object.addEventListener(p, handles[p], false)
        }
        if (typeof node === 'string') {
            node = document.getElementById(node)
        }
        if (insertflg != true) {
            if (node) 
                node.appendChild(object)
        }
        else {
            if (node) 
                node.insertBefore(object, node.firstChild)
        }
        return object
    }  
    
    SSPUtil.openPage =  function openPage(val,flg){
        if(flg){
            gBrowser.selectedTab = gBrowser.addTab(val);
        }else{
            gBrowser.loadURI(val);
        }
    }
}

 function SSPS() {
     
  var mapping = {}
  var ce = SSPUtil.ce;
  var $ = SSPUtil.$;
  
  // 初始化入口
  function onLoad() {
      
        // 地址栏加入图标，图标加入click事件
        ce('image', 'urlbar-icons', {
            src: 'chrome://sspage/skin/web_site.ico',
            id:'ssp_ico'},{
	    click:popup}) 
 	
	// popuoset加入一个menupopup 用于显示指定页的菜单项
	// processor 打开指定页面
	// showing 重新生成菜单
        ce('menupopup', 'sspage_menu_root',{
		id:'sspage_popup'},{
		command:processor,
		popupshowing:showing})
        
        // 读取数据
        mapping = SSPUtil.getPref();
  }
  
  function processor(e){
      var url = e.target.getAttribute('href')
      if(url){
          SSPUtil.openPage(url,e.ctrlKey)
      }else{
          if (e.target.id=='ssp_fn_append'){
                append()    
          }else{
                remove()              
          }
          SSPUtil.setPref(mapping)
      }
  }
  
  function showing(e){
      if(e.target.id == 'sspage_popup'){
        removeMenuItem(e.target);
        genMenuItem(e.target);      
      }
  }
  
  
  function removeMenuItem(m){
      while (m.firstChild) {
            m.removeChild(m.firstChild);
       }
  }
  
  // 生成指定页菜单
  function genMenuItem(m){
	var flg = false, cUrl = getUrl();cnt = 1;
	// 加入指定页菜单项
	var siteMap = mapping[getHost()]
	if(siteMap){	
        	for each(var page in siteMap.pages){
			if(page.url == cUrl) flg = true; 
		    	// if(c=='lp') continue;
		    	ce('menuitem', m, {label: page.title, 
				href:page.url, 
				tooltiptext:page.url,
				accesskey : cnt < 10 ? cnt++ : ''})
		}
	}
	
	// 加入一个分隔线
        if(siteMap) ce('menuseparator', m,{id:'ssp_ms'})

        // 显示<append>或者<remove>菜单
        if(flg){
            ce('menuitem', m, {label: 'remove page',id:'ssp_fn_remove',accesskey:'r'})
        }else{
            ce('menuitem', m, {label: 'append page',id:'ssp_fn_append',accesskey:'a'})
        }

	//ce('menuitem', m, {label: 'test',id:'ssp_fn_test',accesskey:'t'},{command:test})
        
        
        // 加入<site>菜单项
        ce('menu', m,{label:'site',id:'ssp_m_m'})
        ce('menupopup', 'ssp_m_m',{id:'ssp_m_com'})
        for each(var site in mapping){
	    var t = site.host
            var p = ce('menu', 'ssp_m_com', {label: t ,href:t, tooltiptext:t})  
            ce('menupopup',p,{host:t},{popupshowing:genSubMenuItem})          
        }
        
  }

  function test(){
  	var eTLDService = Components.classes["@mozilla.org/network/effective-tld-service;1"]
                  .getService(Components.interfaces.nsIEffectiveTLDService);
  	var aURI = gBrowser.currentURI
	alert(eTLDService.getBaseDomain(aURI,1));	
	alert(eTLDService.getPublicSuffix(aURI));	
	alert(eTLDService.getPublicSuffixFromHost(aURI.host));
	alert(eTLDService.getBaseDomainFromHost("http://weibo.com:80/u/1840053881"));
  }
  
  function genSubMenuItem(menu){
      if(menu.target.childNodes.length>0) return;
      var host = menu.target.getAttribute('host')
      var site = mapping[host]; 
      for each(var page in site.pages){
          ce('menuitem',menu.target,{label: page.title,href:page.url,tooltiptext:page.url})          
      }
  }
 
  // 追加页面信息
  function append(){
        var host = getHost() , url = getUrl(), title =  getTitle();
	var pageInfo = {title:title, url:url}
	var siteInfo = mapping[host];
	// 初始站点信息
	if(siteInfo == undefined){
		siteInfo = {host:host, title:"", pages:[]}
		mapping[host] = siteInfo
	}
	// 加入页面信息
	siteInfo.pages.push(pageInfo)
  }
  
  function remove(){
      var host = getHost() , url = getUrl();        
      if (mapping[host]){
	 var pages = mapping[host].pages
	 for(var indx in pages){
	 	if (pages[indx].url == url){
			for(var s = indx; s<=pages.length-2; s++){
				pages[s] = pages[s+1]
			}
			pages.pop();
			if(pages.length==0){
				delete mapping[host]
			}
			break
				
		}
	 }
         //delete mapping[host][url]

      }
  }
  
  function getHost(){
	  return SSPUtil.getHost(gBrowser.currentURI)
  }
  
  function getUrl(){
     return gBrowser.currentURI.spec
  }
  
  function getTitle(){
      return gBrowser.contentDocument.title
  }
  
  function popup (e){
       var node =  e ? e.target:gBrowser.selectedTab  
      $('sspage_popup').openPopup(node, "after_end", 0, 0, false, false)
  }
  
   this.onLoad = onLoad
   
   this.popup = popup;

};

